const express = require('express');
//导入 body-parser
const bodyParser = require('body-parser');
const db = require('./db/db.js');
const StudentModel = require('./models/StudentModel');
const UserModel = require('./models/UserModel');
const md5 = require('md5');
//引入 session 操作的两个包
var session = require("express-session");
var MongoStore = require('connect-mongo');

//声明一个函数
const checkUserLogin = (request, response, next) => {
    //检测当前用户是否已经登录
    if(!request.session.phone){
        return response.redirect('/login');
    }
    next();
}

db(()=>{
    const app = express();
    //设置
    app.set('view engine','ejs');
    app.set('views', __dirname + '/views');
    //设置中间件
    app.use(bodyParser.urlencoded({ extended: false }));
    //设置静态资源中间
    app.use(express.static(__dirname + '/www'));
    //设置 session 的中间件
    app.use(session({
        name: 'sid',   //设置cookie的name，默认值是：connect.sid
        secret: '12312312sajfljaoie$##', //参与加密的字符串（又称签名）
        saveUninitialized: false, //是否为每次请求都设置一个cookie用来存储session的id
        resave: true,//是否在每次请求时重新保存session
        store:MongoStore.create({
            mongoUrl: 'mongodb://127.0.0.1:27017/h50415' //数据库的连接配置
        }),
        cookie: {
            httpOnly: true, // 开启后前端无法通过 JS 操作
            maxAge: 1000 * 20 * 60 // 这一条 是控制 sessionID 的过期时间的！！！
        },
    }));

    //创建路由规则 
    //首页规则
    app.get('/', (request, response) => {
        response.send('首页');
    });

    //显示所有的学员信息
    app.get('/students', checkUserLogin,(request, response) => {
        //读取数据库数据
        StudentModel.find((err, data) => {
            if(err){
                //失败的响应
                response.send('数据读取失败!! 请稍后重试');
            }else{
                response.render('list', {data});
            }
        })
    });

    //显示表单页面
    app.get('/student/create', checkUserLogin, (request, response) => {
        response.render('create');
    });

    //新增学员信息
    app.post('/student/create', checkUserLogin,(request, response) => {
        // console.log(request.body);
        //将数据插入到数据库中
        StudentModel.create(request.body, (err, data) => {
            if(err) {
                response.send('插入失败, 请稍后重试!');
            }else{
                response.send('添加成功');
            }
        })
    });

    //删除某个学员信息
    app.get('/student/:id/delete', checkUserLogin,(request, response) => {
        //获取学员的id
        let _id = request.params.id;
        //删除
        StudentModel.deleteOne({_id: _id}, (err, data) => {
            if(err){
                response.send('删除失败, 请稍后再试');
            }else{
                // response.send('删除成功');
                // response.redirect('/students');
                response.render('success', {
                    msg: '删除成功',
                    url: '/students'
                })
            }
        });
    });

    //修改学员信息
    app.get('/student/:id/edit', checkUserLogin,(request, response) => {
        //获取 URL 中的 id 的参数值
        let _id = request.params.id;
        //读取数据库获取当前学员的信息
        StudentModel.findOne({_id: _id}, (err, data) => {
            if(err) {
                response.send('数据获取失败, 请稍后再试!');
            }else{
                response.render('edit', {data});
            }
        })
    });

    //更新学员信息
    app.post('/student/:id/update', checkUserLogin,(request, response) => {
        //获取表单数据  request.body  {name:'富贵之人', age: 30}
        //更新的条件   
        let _id = request.params.id;
        //更新数据
        StudentModel.updateOne({_id: _id}, {$set: request.body}, (err, data) => {
            if(err) {
                response.send('更新失败, 请稍后重试!!');
            }else{
                response.send('更新成功');
            }
        })
    });

    //用户的注册
    app.get('/signup', (request, response) => {
        response.render('signup');
    });

    //新增用户
    app.post('/signup', (request, response) => {
        //用户的信息存入到数据库  {phone:12312, password:1231231}
        request.body.password = md5(request.body.password);
        UserModel.create(request.body, (err, data) => {
            if(err) {
                response.send('注册失败, 请稍后再试!!');
            }else{
                response.send('注册成功');
            }
        });
    });

    //登录的页面
    app.get('/login', (request, response) => {
        response.render('login');
    });

    //登录操作
    app.post('/login', (request, response) => {
        //检测用户输入内容是否正确
        UserModel.findOne({phone: request.body.phone, password: md5(request.body.password)}, (err, data) => {
            if(err || data===null){
                response.send('登录失败, 请重试');
            }else{
                //写入登录状态
                request.session.phone = data.phone;
                response.send('登录成功');
            }
        })
    });

    app.listen(80, () => {
        console.log('服务已经启动, 端口监听中....');
    });
}, ()=>{
    console.log('连接失败');
})
